package tr.gov.tubitak.uekae.esya.api.xades.example.multiple;

import org.junit.Test;

import tr.gov.tubitak.uekae.esya.api.asn.x509.ECertificate;
import tr.gov.tubitak.uekae.esya.api.smartcard.example.JSmartCardManager;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.Context;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.SignatureMethod;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.SignedDocument;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.XMLSignature;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.document.Document;
import tr.gov.tubitak.uekae.esya.api.xades.example.utils.SampleBase;
import tr.gov.tubitak.uekae.esya.api.xades.example.validation.Validation;
import tr.gov.tubitak.uekae.esya.api.xmlsignature.resolver.Resolver;

import java.io.FileOutputStream;
import java.security.cert.X509Certificate;

/**
 * Counter signature to a parallel signature sample
 * @author suleyman.uslu
 */
public class CounterParallel extends SampleBase {

    public static final String SIGNATURE_FILENAME = "counter_parallel.xml";

    /**
     * Adds counter signature to a parallel detached one
     * @throws Exception
     */
    @Test
    public void signCounterParallel() throws  Exception
    {
        Context context = createContext();

        // read previously created signature
        Document signatureFile = Resolver.resolve(ParallelDetached.SIGNATURE_FILENAME, context);
        SignedDocument signedDocument = new SignedDocument(signatureFile, context);

        // get first signature
        XMLSignature signature = signedDocument.getSignature(0);

        // create counter signature to the first one
        XMLSignature counterSignature = signature.createCounterSignature();

        counterSignature.getSignedInfo().setSignatureMethod(SignatureMethod.RSA_SHA256);

        // false-true gets non-qualified certificates while true-false gets qualified ones
        X509Certificate cert = JSmartCardManager.getInstance().getSignatureCertificate(true, false);

        // add certificate to show who signed the document
        counterSignature.addKeyInfo(new ECertificate(cert.getEncoded()));

        // now sign it by using smart card
        counterSignature.sign(JSmartCardManager.getInstance().getSigner(PIN, cert));

        // signed doc contains both previous signature and now a counter signature
        // in first signature
        signedDocument.write(new FileOutputStream(BASE_DIR + SIGNATURE_FILENAME));
    }

    @Test
    public void validate() throws Exception {
        Validation.validateParallel(SIGNATURE_FILENAME);
    }
}
